package org.example;

import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;

import java.time.Duration;
import java.util.Collections;
import java.util.Objects;
import java.util.Properties;

public class Consumer {
    public static void main(String[] args) {
        String serverList = "192.168.64.2:9092";
        String topic = "topic_test";
        String groupId = "group_test";
        Properties properties = new Properties();
        // 配置key反序列化
        properties.put("key.deserializer","org.apache.kafka.common.serialization.StringDeserializer");
        // 配置value反序列化
        properties.put("value.deserializer","org.apache.kafka.common.serialization.StringDeserializer");
        // 配置kafka 地址
        properties.put("bootstrap.servers",serverList);
        // 配置消费组
        properties.put("group.id",groupId);
        KafkaConsumer<String, String> kafkaConsumer = new KafkaConsumer<>(properties);
        kafkaConsumer.subscribe(Collections.singletonList(topic));
        while (true) {
            ConsumerRecords<String, String> records = kafkaConsumer.poll(Duration.ofMillis(1000));
            if (Objects.isNull(records)) {
                continue;
            }
            for (ConsumerRecord<String, String> record : records) {
                System.out.println(String.format("消费消息：%s", record.value()));

            }
        }
    }
}
